require "Common/define"
require "Logic/Config"
require "Common/functions"

UIStory = {}
HelperFunc.SetUIEnv(UIStory)
local this = UIStory;
this.LuaBehaviour = nil;
this.transform = nil;
this.gameObject = nil;
this.hasInit = nil;
---@type GComponent
this.view = nil;
this.textinfo = nil; --文字描述引导
this.playerImage = nil;  --人物例会
this.playerImage2 = nil;  --人物例会
this.playerDrawObj = nil; --人物spine
this.playerDraw = nil; --人物spine
this.playerDrawWrapper = nil;
this.idleTimer = nil;
this.blackCover = nil; --剧情消失动画
---@type FairyGUI.GGraph
this.effectRoot = nil; --特效生成父节点
this.stateController = nil;  --状态控制器
this.btn_jump = nil; --跳过按钮
this.btn_auto = nil;--自动播放
this.btn_replay = nil;--跳过
this.btnBg = nil;    --点击任意位置
this.Bgfull = nil;--场景背景
this.jumpController = nil;
this.ImgPanelJump = nil;--跳过图
this.txJumptext = nil;--跳过描述
this.txJumpName = nil;--跳过名字
this.btn_JumpNext = nil;--跳过确认
this.btn_Go = nil;--继续剧情
this.isAuto=false; --是否自动剧情
this.hasInit=false;
this.canIntoNext=false;--可以进入下一步
this.isChoose=false;--是否在选择界面
this.NowStoryIDTable={}; --剧情id数组
this.NowStory = nil; --剧情配置
this.NowChapter = nil;--目前剧情章节
this.NowComicTab={};--当前漫画Image
this.comicImage = nil; --漫画预设
this.MovieImage = nil;--当前视频动画s
this.darkScreen = nil; --屏幕暗下动效
this.EffectTime=0;--特效完成时间才能点击
this.effectFxTab={};--特效配置表
this.objEffectTab={};--特效实例化
this.choseConf={};--选择对话下一步表
this.btnChoseNextTab={};--选择剧情按钮
this.talkPlug = nil; --对话包
this.tapStr = nil;--打字机文字
this.tapArr={};--打字机数组
this.tapSpeed=0; --打字速度
this.comicRoot = nil;--漫画父物体
this.talkName = nil; --对话名字
this.UICamera = nil;
this.shakeTransition = nil;  --震屏动效
this.sayWordBg = nil;
this.textinfobackground = nil;--旁白
this.NowStoryBgm = nil;
this.role_liHui1 = nil;
this.drawWrapper1 = nil;
this.DrawingParent1 = nil;
this.Drawingroot1 = nil;
this.role_liHui2 = nil;
this.drawWrapper2 = nil;
this.DrawingParent2 = nil;
this.Drawingroot2 = nil;
this.talkChoose=false;
this.chooseBg = nil;
this.isCreateMat = nil
this.loadedSceneName = ""
this.loadedEffectName = ""
---@type GController
this.mosaicTimerId = nil
this.ctrlMask = nil
this.iconMask = nil
this.mosaic = nil
this.mosaicCtrl = nil
this.playerFaceIcon = nil
this.playerFaceIconDefaultPos = Vector2.New(0,0)
this.ctrlPlayerFaceIconEmoji = nil
this.lastScene = nil
this.bubGra = nil
this.bubWra = nil
this.bubObj = nil
this.delayTimerId = nil
this.speakCtrl = nil
this.transitionOutList = {
    Effect_SceneChangeOut = "Effect_SceneChangeIn",
}
this.PlayerOriginPos = nil
function UIStory.Init()
    local name, package = getUIName(PanelResNames.UIStory);
    panelMgr:Push(name, package, this.onCreate,Config.useLocalUI);
end

function UIStory.finishVideo()
    canIntoNext=true;
end

function UIStory.onCreate(obj)
    view = obj;
    if not UIPackage.GetById("FUI/StoryEmoji") then
        this.isNeedRemovePackage = true;
        AddUIPackageDepend(PanelNames.UIStory, "FUI/StoryEmoji")
    end
    AddUIPackageDepend(PanelResNames.UIStory,"FUI/StoryLiHuiAtlas")
    if not this.hasInit then
        this.hasInit = true;
        this.textinfo=obj:GetChild("textinfo");
        this.textInfoDefaultSize = textinfo.textFormat.size
        stateController = obj:GetController("state");
        this.head = obj:GetChild("head")
        this.headIcon = this.head:GetChild("head"):GetChild("HeadIcon")
        btn_jump=obj:GetChild("btn_jump");
        btnBg=obj:GetChild("btnBg");
        Bgfull=obj:GetChild("Bgfull");
        ImgPanelJump=obj:GetChild("ImgPanelJump");
        txJumptext=obj:GetChild("txJumptext");
        txJumpName=obj:GetChild("txJumpName");
        btn_Go=obj:GetChild("btn_Go");
        btn_JumpNext=obj:GetChild("btn_JumpNext");
        comicImage=obj:GetChild("comicImage");
        darkScreen = obj:GetTransition("darkScreen");
        MovieImage=obj:GetChild("videoImage");
        btn_auto=obj:GetChild("btn_auto");
        btn_replay=obj:GetChild("btn_replay");
        effectRoot=obj:GetChild("effectRoot");
        comicRoot=obj:GetChild("comicRoot");
        talkName=obj:GetChild("talkName");
        textinfobackground=obj:GetChild("textinfobackground");
        this.textInfoBackgroundDefaultSize = textinfobackground.textFormat.size
        jumpController = obj:GetController("jump");
        Drawingroot1= obj:GetChild("draw1r")
        Drawingroot2= obj:GetChild("draw2r")
        DrawingParent1= obj:GetChild("draw1r"):GetChild("draw1");
        DrawingParent2= obj:GetChild("draw2r"):GetChild("draw1");
        chooseBg=obj:GetChild("chooseBg");
        iconMask = obj:GetChild("Mask")
        mosaic = obj:GetChild("mosaic")
        mosaicCtrl = obj:GetController("transition")
        bubGra = obj:GetChild("bubbles")
        speakCtrl = obj:GetController("object")
        this.voiceController = obj:GetController("voice")
        this.mosicCtrl = nil
        this.ctrlMask = obj:GetController("mask")
        local playerRoot = obj:GetChild("PlayerImage")
        this.playerRoot = playerRoot
        this.playerImage=playerRoot:GetChild("Icon_PlayerImage");
        this.playerFaceIcon = playerRoot:GetChild("Icon_Face")
        this.playerFaceIconDefaultPos:Set(this.playerFaceIcon.x,this.playerFaceIcon.y)
        this.ctrlPlayerFaceIconEmoji = playerRoot:GetController("emoji")
        if this.PlayerOriginPos == nil then
            this.PlayerOriginPos = this.playerRoot.xy
        end
        this.curAutoTime = 0
        this.autoTime = 0
        this.defaultAutoTime = 3
        btnChoseNextTab = {}
        for i = 1, 4 do
            local tempChoseBtn=obj:GetChild("chose"..(i - 1));
            table.insert(btnChoseNextTab,tempChoseBtn);
        end
        ---------------------------------------
        --- 弹幕系统相关
        ---------------------------------------
        this.btn_bullet_chat = obj:GetChild("btn_bulletChat");
        if Config.OpenCommentAndBullet then
            if logicMgr.FuncOpenManager.isOpen(Config.FuncOpenType.BulletChat) then
                this.btn_bullet_chat.visible = true
                this.btn_bullet_chat.touchable = true
            else
                this.btn_bullet_chat.visible = false
                this.btn_bullet_chat.touchable = false
            end
        else
            this.btn_bullet_chat.visible = false
            this.btn_bullet_chat.touchable = false
        end
        this.btn_bullet_chat_title = this.btn_bullet_chat:GetChild("title")
        this.btn_bullet_chat_title.text = getLanguage("BulletChat_BulletOn")
        this.btn_bullet_chat_ctrl = this.btn_bullet_chat:GetController("state")
        this.cur_bullet_chat_open = true
        this.btn_bullet_chat_ctrl.selectedIndex = 1

        this.playerDrawObj = obj:GetChild("draw")
        ---------------------------------------
        --- end
        ---------------------------------------
        this.addEvent();
    end
    if this.PlayerOriginPos then
        this.playerRoot.xy = this.PlayerOriginPos
    end
    btn_replay.visible = false;
    this.sceneTextures = {}
    --AudioManager.IsPlay(false,AudioManager.WwiseFlagEnum.Sound)
    this.InitChapter(logicMgr.StoryMgr.willChap)
    logicMgr.StoryMgr.willChap = 0
    logicMgr.GuideMgr.Pause(GuideMgr.PauseType.StoryPause)
end

function UIStory.addEvent()
    btn_jump.onClick:Add( this.forceEnd);--this.JumpThisTrigger
    btn_JumpNext.onClick:Add( this.forceEnd);
    btn_Go.onClick:Add(this.CloseJump);
    btn_auto.onClick:Add( this.autoPlay);
    btnBg.onClick:Add( this.ConfirmJumpThisTrigger);
    for i = 1, 4 do
        btnChoseNextTab[i].onClick:Add( function() this.ChoseNext(i); end);
    end
    this.btn_bullet_chat.onClick:Add( this.OperateBulletChat ) --添加弹幕系统操作按钮事件
end

function UIStory.removeEvent()
    btn_jump.onClick:Remove( this.forceEnd);
    btn_JumpNext.onClick:Remove( this.forceEnd);
    btn_Go.onClick:Remove(this.CloseJump);
    btn_auto.onClick:Remove( this.autoPlay);
    btnBg.onClick:Remove( this.ConfirmJumpThisTrigger);
    for i = 1, 4 do
        btnChoseNextTab[i].onClick:Remove( function() this.ChoseNext(i); end);
    end
    this.btn_bullet_chat.onClick:Remove( this.OperateBulletChat ) --删除弹幕系统操作按钮事件
end

function UIStory.LocalListenEvent()
end

function UIStory.LocalCloseEvent()
end

function UIStory.OnDestroy()
    this.hasInit=false;
    this.removeEvent();
    this.btn_bullet_chat = nil
    this.cur_bullet_chat_open = false
    this.btn_bullet_chat_ctrl.selectedIndex = 0
    this.btn_bullet_chat_title = nil
    DestoryUI(PanelNames.UIBulletChat)
    if effectWrap then
        effectWrap:Dispose()
        effectWrap = nil
    end
    if this.delayTimerId then
        utimer.remove(this.delayTimerId)
        this.delayTimerId = nil
    end

    if this.last_effect_sound then
        AudioManager.Stop(this.last_effect_sound, nil, AudioManager.WwiseFlagEnum.Sound)
    end

    if this.last_talk then
        AudioManager.Stop(this.last_talk, nil, AudioManager.WwiseFlagEnum.Voice)
    end

    if this.isNeedRemovePackage and UIPackage.GetById("FUI/StoryEmoji") then
        UIPackage.RemovePackage("FUI/StoryEmoji")
    end
    if UIPackage.GetById("FUI/StoryLiHuiAtlas") then
        UIPackage.RemovePackage("FUI/StoryLiHuiAtlas")
    end

    if this.playerDraw ~= nil then
        destroyImmediate(this.playerDraw);
        this.playerDraw = nil
    end

    if this.playerDrawWrapper then
        this.playerDrawWrapper:Dispose()
        this.playerDrawWrapper = nil
    end

    if idleTimer~=nil then
        idleTimer:Stop();
    end

    btnChoseNextTab = {}
end

function UIStory.OnEnable()
    isAuto=false;
    this.LocalListenEvent();
end

function UIStory.OnDisable()
    this.LocalCloseEvent();
    if this.delayTimerId then
        utimer.remove(this.delayTimerId)
        this.delayTimerId = nil
    end
    for i=1,#NowComicTab do
        destroyImmediate(NowComicTab[i]);
    end
    utimer.remove(this.autoPlayTimerId)
    this.autoPlayTimerId = nil
    NowComicTab={};
    AudioManager.IsPlay(true,AudioManager.WwiseFlagEnum.Sound)
    if this.effectWrap then
        destroy(this.effectWrap.wrapTarget)
    end
    this.loadedPlayerIconName = ""
    this.loadedSceneName = ""
    for k,v in pairs(this.sceneTextures) do
        resMgr:DestroySprite(k)
    end
    table.clear(this.sceneTextures)
end
--初始化章节
function UIStory.InitChapter(chapID)
    logicMgr.StoryMgr.cur_chapter_id = chapID
    if Config.OpenCommentAndBullet and logicMgr.FuncOpenManager.isOpen(Config.FuncOpenType.BulletChat) then
        chatHandler.HttpGetLevitateCommentInfo( chapID )
    end
    if Config.OpenCommentAndBullet then
        if logicMgr.FuncOpenManager.isOpen(Config.FuncOpenType.BulletChat) then
            this.btn_bullet_chat.visible = true
            this.btn_bullet_chat.touchable = true
            local key = logicMgr.HeroManager.GetRoleId().."uistory_switch"
            local story_switch = Util.GetPlayerPrefs(key)

            --if chatHandler.IsOpenBulletFunction() or (story_switch and story_switch == "true") then
            this.btn_bullet_chat_title.text = getLanguage("BulletChat_BulletOn")
            this.cur_bullet_chat_open = true
            this.btn_bullet_chat_ctrl.selectedIndex = 1
            showUI(PanelNames.UIBulletChat, 1)
            --else
            --    this.btn_bullet_chat_title.text = getLanguage("BulletChat_BulletOff")
            --    this.btn_bullet_chat_ctrl.selectedIndex = 0
            --    this.cur_bullet_chat_open = false
            --end
        else
            this.btn_bullet_chat.visible = false
            this.btn_bullet_chat.touchable = false
        end
    end
    this.view:GetChild("n31").alpha = 1
    this.view:GetChild("n43").alpha = 1
    this.view:GetChild("n43").visible = true
    this.textinfo.text="";
    textinfobackground.text="";
    canIntoNext=false;
    stateController.selectedIndex = 0;
    jumpController.selectedIndex = 0;
    NowChapter=G.dataTable["t_storymain"][tostring(chapID)];
    choseConf={}
    if(isAuto==false)then
        btn_auto.text=getLanguage("Story_1");
    end
    btn_auto.visible = (NowChapter.f_Auto==1);
    btn_jump.visible = (NowChapter.f_Jump==1);
    Bgfull.visible = false;
    Bgfull.alpha = 1
    this.playerRoot.alpha = 1
    chooseBg.visible=false;
    NowStoryIDTable = {}
    for k,v in pairs(NowChapter.f_contentID) do
        table.insert(NowStoryIDTable,v)
    end
    if(NowChapter.f_StoryType==1)then
        this.InitComic();
    end
    if(NowChapter.f_StoryType==2 or NowChapter.f_StoryType==3)then
        this.InitContent();
    end
    if(NowChapter.f_StoryType==4)then
        this.InitVideo();
    end
end

function UIStory.InitComic()
    for i = 1, #NowStoryIDTable do
        local tempConfComic=G.dataTable["t_storycomic"][tostring(NowStoryIDTable[i])];
        this.PlayTalk(tempConfComic.f_Name);
        this.PlayBgm(tempConfComic.f_bgm);

        local ComicPic=newObject(comicImage.gameObject);
        local confComicPos= (tempConfComic.f_pos);
        resMgr:LoadSpritePrefab(tempConfComic.f_StoryRes,function(sp)
            ComicPic:GetComponent("Image").sprite = sp;
            ComicPic.transform.parent=comicRoot;
            ComicPic:GetComponent("RectTransform").sizeDelta=Vector2(confComicPos[3],confComicPos[4]);
            Util.Lua_SetLocalScaleXYZ(ComicPic.transform,1,1,1)
            ComicPic.gameObject:SetActive(true);
        end);
        if(i%2>0)then
            ComicPic:GetComponent("RectTransform").anchoredPosition=Vector2(confComicPos[1]-1238,confComicPos[2]);
        else
            ComicPic:GetComponent("RectTransform").anchoredPosition=Vector2(confComicPos[1]+1238,confComicPos[2]);
        end
        table.insert(NowComicTab,ComicPic);
        if(i==#NowStoryIDTable)then
            local TweenPic=ComicPic:GetComponent("RectTransform"):DOAnchorPosX(confComicPos[1],0.5):OnComplete(this.completeComicShow);
            TweenPic:SetDelay(i*0.6);
        else
            local TweenPic=ComicPic:GetComponent("RectTransform"):DOAnchorPosX(confComicPos[1],0.5);
            TweenPic:SetDelay(i*0.6);
        end
    end
end

function UIStory.PlayBgm(sendBgm)
    if string.IsNilOrEmpty(sendBgm) then return end
    --播放剧情背景音乐
    AudioManager.Play(sendBgm)
    --[[local tempBgm=G.dataTable["t_bgm"][sendBgm].f_MusicLoop
    if(NowStoryBgm~=tempBgm)then
         NowStoryBgm=tempBgm;
        resMgr:LoadAudioPrefab("sound/bg/"..NowStoryBgm,function(sClip)
             bgmPlug.clip = sClip;
            bgmPlug.loop=true;
            bgmPlug:Play();
         end)
    end
    bgmPlug:Stop();--]]
end
function UIStory.SoundEnd()
    this.autoTime = 0
end
function UIStory.PlayTalk(talk)
    if string.IsNilOrEmpty(talk) then return end
    this.autoTime = 20
    AudioManager.Stop(UIStory.last_talk, nil, AudioManager.WwiseFlagEnum.Voice)
    UIStory.last_talk = AudioManager.Play(talk,nil,this.SoundEnd)
    local Sval=0.5;
    local value=Util.GetPlayerPrefs("soundValue")
    if(value~=nil)then
        Sval=tonumber(value);
    end
    --[[if(talk~="")then
        local soundpath = "sound/hero/"..talk;
        resMgr:LoadAudioPrefab(soundpath,function(sClip)
            talkPlug:Stop();
            talkPlug.clip = sClip;
            talkPlug:Play();
        end)
    end
    soundMgr:PlayCV(soundpath,nil);]]
end
function UIStory.PlaySoundEffect()
    if not string.IsNilOrEmpty(NowStory.f_soundEffect) then
        if this.last_effect_sound then
            AudioManager.Stop(this.last_effect_sound, nil, AudioManager.WwiseFlagEnum.Sound)
        end

        this.last_effect_sound = AudioManager.Play(NowStory.f_soundEffect)
    end
    --[[if not string.IsNilOrEmpty(NowStory.f_bgm) then
        AudioManager.Play(NowStory.f_bgm)
    end--]]

    this.clickable_sound = true
    AudioManager.Stop(UIStory.last_talk, nil, AudioManager.WwiseFlagEnum.Voice)
    this.last_talk = ""
    if not string.IsNilOrEmpty(NowStory.f_Voice) then
        local delay = tonumber(NowStory.f_Voice[2])
        if delay > 0 then
            this.clickable_sound = false
            utimer.delayCall(this.DoPlayVoice,delay)
        else
            this.DoPlayVoice()
        end
    end
end
function UIStory.DoPlayVoice()
    this.clickable_sound = true
    this.autoTime = 20
    this.last_talk =  AudioManager.Play(NowStory.f_Voice[1],nil,this.SoundEnd)

end
--漫話播完
function UIStory.completeComicShow()
    canIntoNext=true;
    NowStoryIDTable={};
end
function UIStory.IsClickable()
    return this.clickable_dialog and this.clickable_transition and this.clickable_sound
end

function UIStory.delayIdle() -- 调用loop的idea
    if not this.playerDraw then
        return;
    end
    local model = this.playerDraw;
    if not HelperFunc.IsNull(model)then
        model:GetComponent("SkeletonGraphic").unscaledTime = true
        model:GetComponent("SkeletonGraphic").AnimationState:SetAnimation(0,"idle1",true);
        this.lastFightRole = 1;
    end
end

function UIStory.InitDraw()
    local pos = nil
    local draw = ""
    if(NowStory.f_leftSide~="") then
        draw = NowStory.f_leftSide
        pos = NowStory.f_leftSideinfo
    end
    if(NowStory.f_centerSide~="") then
        draw = NowStory.f_centerSide
        pos = NowStory.f_centerSideinfo
    end
    if (NowStory.f_rightSide ~= "") then
        draw = NowStory.f_rightSide
        pos = NowStory.f_rightSideinfo
    end
    --人物显示
    if string.IsNilOrEmpty(draw[1]) then
        this.playerRoot.visible = false
        if this.playerDraw ~= nil then
            this.playerDraw:SetActive(false)
        end
        return
    end
    if this.loadedPlayerIconName  == draw[1] then
        playerImage.visible  = true;
        this.playerRoot.visible = true
    else
        if string.IsNilOrEmpty(draw[2]) or draw[2] ~= 2 then
            stateController.selectedIndex = 1;
            this.loadedPlayerIconName = draw[1]
            playerImage.visible  = true;
            this.playerRoot.visible = true
            playerImage.url = ""..draw[1]
        end
    end
    if draw[2] == 1 then
        if this.playerDraw ~= nil then
            this.playerDraw:SetActive(false)
        end
        playerImage.visible = true
        playerImage.material = Material(Shader.Find("Unlit/textureMask"))
        --playerImage.material:SetTexture("_TextureSample0",playerImage.texture.nativeTexture)
        if draw[2] == 1 then
            playerImage.material:SetFloat("_heiseRange",0.7)
            playerImage.material:SetFloat("_heisePower",1.89)
        else
            playerImage.material:SetFloat("_heiseRange",0.716)
            playerImage.material:SetFloat("_heisePower",0.69)
        end
    elseif draw[2] == 2 then
        playerImage.visible = false

        local path = HeroManager.GetHeroDrawingPath(draw[1], nil);
        if this.playerDraw == nil or this.playerDraw.name ~= path then
            this.lastFightRole = nil;
            resMgr:LoadModelPrefab(path, function(go)
                if this.playerDrawWrapper == nil then
                    this.playerDrawWrapper = GoWrapper.New();
                end
                if this.playerDraw ~= nil then
                    destroyImmediate(this.playerDraw);
                    this.playerDraw = nil
                end
                if idleTimer~=nil then
                    idleTimer:Stop();
                end
                this.playerDraw = newObject(go);
                this.playerDraw.name = path;
                this.playerDraw:SetActive(true)
                this.playerDraw:AddComponent(TCanvas);
                this.playerDrawWrapper:SetWrapTarget(this.playerDraw, true)
                this.playerDrawObj:SetNativeObject(this.playerDrawWrapper)
                this.playerDraw:GetComponent("SkeletonGraphic").unscaledTime = true
                if NowStory.f_fightRole ~= nil and NowStory.f_fightRole == "2" then
                    this.lastFightRole = 2;
                    this.playerDraw:GetComponent("SkeletonGraphic").AnimationState:SetAnimation(0, "idle2", false);
                    local idleAniTime = this.playerDraw:GetComponent("SkeletonGraphic").AnimationState.Data.SkeletonData:FindAnimation("idle2").Duration;
                    if idleTimer == nil then
                        idleTimer = Timer.New(this.delayIdle,idleAniTime,1,true);
                    else
                        idleTimer:Reset(this.delayIdle,idleAniTime,1,true);
                    end
                    idleTimer:Start();
                else
                    this.lastFightRole = 1;
                    this.playerDraw:GetComponent("SkeletonGraphic").AnimationState:SetAnimation(0, "idle1", true);
                end

                if NowStory.f_locationinfo ~= nil then
                    local tempPos = Vector3.New(NowStory.f_locationinfo[1], NowStory.f_locationinfo[2], 0)
                    Util.Lua_SetLocalPositionXYZ(this.playerDraw.transform, tempPos.x, tempPos.y, tempPos.z)
                    Util.Lua_SetLocalScaleXYZ(this.playerDraw.transform, pos[3], pos[3], pos[3]);
                end
            end,true)
        else
            if this.playerDraw ~= nil then
                this.playerDraw:SetActive(true)
            end
            if idleTimer~=nil then
                idleTimer:Stop();
            end
            if this.playerDraw ~= nil and NowStory.f_locationinfo ~= nil then
                local tempPos = Vector3.New(NowStory.f_locationinfo[1], NowStory.f_locationinfo[2], 0)
                Util.Lua_SetLocalPositionXYZ(this.playerDraw.transform, tempPos.x, tempPos.y, tempPos.z)
                Util.Lua_SetLocalScaleXYZ(this.playerDraw.transform, pos[3], pos[3], pos[3]);
            end

            if this.playerDraw ~= nil and NowStory.f_fightRole ~= nil and NowStory.f_fightRole == "2" and this.lastFightRole ~= 2 then
                this.lastFightRole = 2;
                this.playerDraw:GetComponent("SkeletonGraphic").AnimationState:SetAnimation(0, "idle2", false);
                local idleAniTime = this.playerDraw:GetComponent("SkeletonGraphic").AnimationState.Data.SkeletonData:FindAnimation("idle2").Duration;
                if idleTimer == nil then
                    idleTimer = Timer.New(this.delayIdle,idleAniTime,1,true);
                else
                    idleTimer:Reset(this.delayIdle,idleAniTime,1,true);
                end
                idleTimer:Start();
            elseif this.lastFightRole ~= 1 then
                if this.playerDraw ~= nil then
                    this.lastFightRole = 1;
                    this.playerDraw:GetComponent("SkeletonGraphic").AnimationState:SetAnimation(0, "idle1", true);
                end
            end
        end
    else
        this.lastFightRole = nil;
        if this.playerDraw ~= nil then
            this.playerDraw:SetActive(false)
        end
        playerImage.visible = true
        playerImage.material = Material(Shader.Find("FairyGUI/Image"))
    end
    if not string.IsNilOrEmpty(pos) then
        playerImage:SetXY(tonumber(pos[1]),tonumber(pos[2]));
        playerImage:SetScale(tonumber(pos[3]),tonumber(pos[3]));
    end
    this.InitFaceEmotion()
end
--入场
function UIStory.TransitionEnter()
    local count = 0
    mosaicCtrl.selectedIndex = 0
    if NowStory.f_sceneChange ~= "" then
        if NowStory.f_sceneChange[2] == 0 then
            count = count + this.Transition(NowStory.f_sceneChange[1])
        else
            this.playerFaceIcon.visible = false
            playerImage.visible  = false
            count = count + this.Transition("Effect_SceneChangeIn")
            mosaicCtrl.selectedIndex = 1
            resMgr:LoadSpritePrefab(lastScene,function(sp)
                this.sceneTextures[lastScene] = 1
                mosaic.texture = NTexture.New(sp.texture);
                mosaic.alpha = 1
                mosaic:SetScale(1.1,1.1)
                if NowStory.f_sceneChange[1] == "baiyechuang" then
                    local num = 6.5
                    mosaic.shader = "Unlit/"..NowStory.f_sceneChange[1]
                    if mosaicTimerId then
                        utimer.remove(mosaicTimerId)
                        mosaicTimerId = nil
                    end
                    local time = 0
                    mosaic.material:SetFloat("_Blend",0)
                    mosaicTimerId = utimer.timeCall(function()
                        time = time + 100
                        mosaic.material:SetFloat("_Blend",time*num / 1000)
                        if time > 1000 then
                            mosaic.material:SetFloat("_Blend",num)
                            utimer.remove(mosaicTimerId)
                            mosaicTimerId = nil
                            mosaicCtrl.selectedIndex = 0
                        end
                    end,100,-1)
                else
                    count = count + this.Transition("Effect_BgMo")
                end
            end);
        end
    end
    if NowStory.f_roleZoom ~= "" then
        count = count + this.Transition(NowStory.f_roleZoom)
    end
    if NowStory.f_roleAppear ~= "" then
        count = count + this.Transition(NowStory.f_roleAppear)
    end
    if NowStory.f_sceneZoom ~= "" then
        count = count + this.Transition(NowStory.f_sceneZoom)
    end
    if NowStory.f_shakeScreen ~= "" then
        count = count + this.Transition(NowStory.f_shakeScreen)
    end
    if NowStory.f_shakeRole ~= "" then
        count = count + this.Transition(NowStory.f_shakeRole)
    end
    this.transitionCount = count
    this.clickable_transition = count == 0
end
--出场
function UIStory.TransitionExit()
    local count = 0
    if NowStory.f_roleDisappear ~= "" then
        count = count + this.Transition(NowStory.f_roleDisappear,0,true)
    end
    if not string.IsNilOrEmpty(NowStory.f_sceneDisappear) then
        count = count + this.Transition(NowStory.f_sceneDisappear,0,true)
        if this.playerDraw ~= nil then
            this.playerDraw:SetActive(false)
        end
    end
    this.clickable_transition = count == 0
    this.transitionCount = count
    if this.transitionCount == 0 then
        this.TransitionExitDone(true)
    end
end
function UIStory.Transition(name,delay,isExit)
    if not delay then delay = 0 end
    if name == nil or type(name) ~= "string" then
        logError("ui动效名错误: "..tostring(name))
        return 0
    end
    local transition = this.view:GetTransition(name)
    if transition then
        if isExit then
            transition:Play(1,delay,this.TransitionExitDone)
            this.Log("Transition exit [",name,"]")
        else
            transition:Play(1,delay,this.TransitionEnterDone)
            this.Log("Transition enter [",name,"]")
        end
        return 1
    else
        logError("找不到ui动效: "..name)
    end
    return 0
end
function UIStory.TransitionEnterDone()
    this.Log("Transition Enter [done] ")
    this.transitionCount = this.transitionCount - 1
    if this.transitionCount <= 0 then
        this.clickable_transition = true
    end
end
function UIStory.TransitionExitDone(ignore)
    if not ignore then
        this.transitionCount = this.transitionCount - 1
        this.Log("Transition Exit [done] ")
    end
    if this.transitionCount <= 0 then
        this.clickable_transition = true
        if(#NowStoryIDTable>1)then
            table.remove(NowStoryIDTable,1);
            lastScene = NowStory.f_scene
            this.InitContent();
            return;
        end
        if(NowChapter.f_nextChapter~=0)then
            this.InitChapter(NowChapter.f_nextChapter);
        else
            isAuto=false;
            btn_auto.text=getLanguage("Story_1");
            this.closeThis();
        end
    end
end
--单色场景蒙版
function UIStory.InitScreenMask()
    if string.IsNilOrEmpty(this.NowStory.f_sceneMask) then
        this.ctrlMask.selectedIndex = 0
        return
    end
    local num = this.NowStory.f_sceneMask[1]
    iconMask.alpha = this.NowStory.f_sceneMask[2]
    if num == nil then
        logError("字段f_sceneMask 应为number  "..this.NowStory.f_sceneMask)
        return
    end
    this.ctrlMask.selectedIndex = num
    if num == 6 then
        resMgr:LoadModelPrefab("UIEff/UI_paopao_01", function(go)
            if bubObj ~= nil then
                destroyImmediate(bubObj);
                bubObj= nil
            end
            if not bubWra then
                bubWra = GoWrapper.New()
            end
            bubObj= newObject(go);
            bubObj:AddComponent(TCanvas);
            bubObj:AddComponent(TChangeSortingOrder)
            bubWra:SetWrapTarget(bubObj, false)
            bubGra:SetNativeObject(bubWra)
            Util.Lua_SetLocalPositionXYZ(bubObj.transform, 0,0, 0)
        end);
    end
    local spineObj = this.view:GetChild("spine_"..num)
    if spineObj then
        Util.PlayAction(spineObj.wrapTarget, "idle", false);
    end
end
--玩家脸部表情
function UIStory.InitFaceEmotion()
    local em = this.NowStory.f_emotion
    if string.IsNilOrEmpty(em) then
        this.playerFaceIcon.visible = false
        return
    end
    if #em ~= 4 then
        logError("不是json格式 "..this.NowStory.f_emotion)
        return
    end
    if this.playerImage.texture ~= nil then
        this.playerFaceIcon.visible = true
    else
        this.playerFaceIcon.visible = false
        utimer.delayCall(function ()
            this.playerFaceIcon.visible = true
        end, 1)
    end
    --this.playerFaceIcon.visible = true
    this.playerFaceIcon.url = "ui://StoryEmoji/"..em[1]
    if em[4] ~= 0 then
        this.playerFaceIcon.material =Material(Shader.Find("Unlit/textureMask"))
        this.playerFaceIcon.material:SetTexture("_TextureSample0",this.playerFaceIcon.texture.nativeTexture)
        this.playerFaceIcon.material:SetFloat("_heiseRange",1)
        this.playerFaceIcon.material:SetFloat("_heisePower",0)
    else
        this.playerFaceIcon.material = Material(Shader.Find("FairyGUI/Image"))
    end
    this.playerFaceIcon.x = this.playerFaceIconDefaultPos.x + tonumber(em[2])
    this.playerFaceIcon.y = this.playerFaceIconDefaultPos.y + tonumber(em[3])
end
function UIStory.InitScene()
    local name = this.NowStory.f_scene
    if string.IsNilOrEmpty(name) then
        Bgfull.visible = false
        return
    end
    if this.loadedSceneName ~= name then
        this.loadedSceneName = name
        resMgr:LoadSpritePrefab(name,function(sp)
            Bgfull.visible = true;
            this.sceneTextures[name] = 1
            Bgfull.texture = NTexture.New(sp.texture);
        end);
    end
end
--特殊表情符号
function UIStory.InitEmoji()
    if string.IsNilOrEmpty(this.NowStory.f_specialEmotion) then
        this.ctrlPlayerFaceIconEmoji.selectedIndex = 0
        return
    end
    local num = tonumber(this.NowStory.f_specialEmotion)
    this.ctrlPlayerFaceIconEmoji.selectedIndex = num
end
function UIStory.InitSceneParticle()
    local name = this.NowStory.f_particleEffects
    if this.effectWrap == nil then
        this.effectWrap = GoWrapper.New()
    end
    if string.IsNilOrEmpty(name) and this.effectWrap then
        destroy(this.effectWrap.wrapTarget)
        return
    end
    if this.loadedEffectName == name then
        return
    end
    if this.effectWrap == nil then
        this.effectWrap = GoWrapper.New()
    end
    this.loadedEffectName = name
    destroy(this.effectWrap.wrapTarget)
    resMgr:LoadModelPrefab(name,function(obj)
        local go = newObject(obj)
        this.effectRoot.visible = true
        go:AddComponent(TCanvas)
        go:AddComponent(TChangeSortingOrder)
        this.effectWrap.wrapTarget = go
        this.effectRoot:SetNativeObject(this.effectWrap)
        Util.Lua_SetLocalPositionXYZ(go.transform,0,0,0)
    end)
end
--对话
function UIStory.InitDialog()
    this.clickable_dialog = true
    if this.dialogTimerId then
        utimer.remove(this.dialogTimerId)
        this.dialogTimerId = nil
    end
    if string.IsNilOrEmpty(this.NowStory.f_StoryContent) then
        stateController.selectedIndex = 0;
        return
    end
    if(NowStory.f_name~="")then
        if NowStory.f_name=="StorySpeak002" or NowStory.f_name =="StorySpeak007" then
            speakCtrl.selectedIndex = 0
        else
            speakCtrl.selectedIndex = 1
        end
    else
        speakCtrl.selectedIndex = 2
    end
    if this.NowStory.f_dialogDelay < 0.0001 then
        this.DoInitDialog()
    else
        this.clickable_dialog = false
        this.dialogTimerId = utimer.delayCall(this.DoInitDialog,this.NowStory.f_dialogDelay)
    end
end
function UIStory.DoInitDialog()
    this.clickable_dialog = true
    textinfo.text="";
    textinfobackground.text="";

    if(NowStory.f_name~="")then
        talkName.text=getLanguage(NowStory.f_name);
    else
        talkName.text="";
    end
    if(NowStory.f_textType ~= "1")then
        stateController.selectedIndex = 0;
        textinfobackground.text=getLanguage(NowStory.f_StoryContent);
        if NowStory.f_textSize == 0 then
            textinfobackground.textFormat.size = this.textInfoBackgroundDefaultSize
        else
            textinfobackground.textFormat.size = NowStory.f_textSize
        end
        textinfobackground.textFormat = textinfobackground.textFormat
    else
        stateController.selectedIndex = 1;
        if NowStory.f_textSize == 0 then
            textinfo.textFormat.size = this.textInfoDefaultSize
        else
            textinfo.textFormat.size = NowStory.f_textSize
        end
        textinfo.textFormat = textinfo.textFormat
        talkChoose=true;
        canIntoNext=false; --中断剧情，出发打字机
        tapStr=getLanguage(NowStory.f_StoryContent);
        local temstr=Util.StringToArr(tapStr);
        tapArr=string_split(temstr,"&");
        textinfo.text=tapArr[1];
        tapSpeed=NowStory.f_textSpeed/1000;
        local index = 1
        if this.coTapText then
            utimer.remove(this.coTapText)
            this.coTapText = nil
        end
        this.coTapText= utimer.timeCall(function()
            index = index +1
            this.TapText(index)
        end ,-1,NowStory.f_textSpeed)
        if string.IsNilOrEmpty(NowStory.f_speakIcon) then
            this.head.visible = false
        else
            this.head.visible = true
            this.headIcon.url = EnumConst.AtlasPath.ICONAtlas..NowStory.f_speakIcon
        end
    end
end
function UIStory.InitChoose()
    for i = 1, 4 do
        local tempBtn=btnChoseNextTab[i];
        tempBtn.visible = false;
    end
    if(NowStory.f_storyChose == "")then
        talkChoose=false;
        return false
    end
    --chooseBg.visible=true;
    Bgfull.visible = true;
    if(talkChoose)then
        stateController.selectedIndex = 5;
    else
        stateController.selectedIndex = 2;
    end
    isChoose=true;--中断剧情，触发选择题

    local subStr=string.split(NowStory.f_storyChose,";")

    for i = 1,#subStr do
        choseConf[i] = string.split(subStr[i],",")
    end

    for i = 1, #choseConf do
        local tempBtn=btnChoseNextTab[i];
        tempBtn.visible = true;
        tempBtn.text=getLanguage(choseConf[i][1]);
    end
    return true;
end
function UIStory.InitContent()
    canIntoNext=true;
    logicMgr.StoryMgr.cur_story_id = NowStoryIDTable[1]
    if Config.OpenCommentAndBullet and logicMgr.FuncOpenManager.isOpen(Config.FuncOpenType.BulletChat) then
        if this.cur_bullet_chat_open and this.cur_bullet_chat_open == true then
            local net_data = chatHandler.GetLevitateCommentInfo( logicMgr.StoryMgr.cur_chapter_id,  NowStoryIDTable[1] )
            if net_data then
                chatHandler.PlayNetStoryComment( net_data )
            end
            chatHandler.LocalStoryBullet()
        end
    end
    NowStory=G.dataTable["t_story"][tostring(NowStoryIDTable[1])]
    if NowStory == nil then
        logError("找不到t_story by id："..NowStoryIDTable[1])
        return ;
    end
    if not string.IsNilOrEmpty(NowStory.f_Voice) then
        this.voiceController.selectedIndex = 1;
    else
        this.voiceController.selectedIndex = 0;
    end
    textinfo.text="";
    textinfobackground.text="";
    --talkName.text="";
    this.PlayBgm(NowStory.f_bgm);
    this.PlaySoundEffect()
    if this.InitChoose() then
        this.InitDialog()
        return
    end
    isChoose = false;
    this.InitDraw()
    this.TransitionEnter()
    this.InitScreenMask()
    if this.delayTimerId then
        utimer.remove(this.delayTimerId)
        this.delayTimerId = nil
    end
    if NowStory.f_sceneChange ~= "" then
        this.delayTimerId = utimer.timeCall(this.InitEmoji,1250,1)
    else
        this.InitEmoji()
    end
    this.InitScene()
    this.InitSceneParticle()
    this.InitDialog()

end

function UIStory.InitVideo()
    local videopath=NowChapter.f_contentID
    if(videopath=="")then
        canIntoNext=true;
    end
end

function UIStory.ShowJump()

end

function UIStory.ChoseNext(index)
    local indexChoseCon=choseConf[index][2]
    if indexChoseCon ~= "" then
        NowStoryIDTable={};
        this.InitChapter(indexChoseCon);
    else
        chooseBg.visible = false
        this.TransitionExit()
    end
end

function UIStory.TapText(i)
    --for i = 2, #tapArr do
    --coroutine.wait(tapSpeed);
    local tInfo
    if this.stateController.selectedIndex == 0 then
        tInfo = textinfobackground
    else
        tInfo = textinfo
    end
    tInfo.text=tInfo.text..tapArr[i];
    if(i==#tapArr)then
        tapArr={};
        canIntoNext=true;
        tInfo.text=tapStr;
        if this.coTapText then
            utimer.remove(this.coTapText)
            this.coTapText = nil
        end
    end
    -- end
end
--自动播放引导
function UIStory.OnUpdate()
    this.updateChapter();
end

function UIStory.updateChapter()
    if(isAuto==false)then
        return;
    end
    if this.curAutoTime < this.autoTime then
        this.curAutoTime = this.curAutoTime + 0.1
        return
    end
    this.ResetAutoTime()
    if(#choseConf>0)then
        local indexChoseCon=choseConf[1][2]
        if indexChoseCon ~= "" then
            this.InitChapter(indexChoseCon);
        else
            chooseBg.visible = false
            this.TransitionExit()
        end
    else
        this.ConfirmJumpThisTrigger();
    end
end
--確認强制跳過章節
function UIStory.forceEnd()
    if this.dialogTimerId then
        utimer.remove(this.dialogTimerId)
        this.dialogTimerId = nil
    end
    NowStoryIDTable={};
    if(#tapArr~=0)then
        textinfo.text=tapStr;
        tapArr={};
        canIntoNext=true;
        if this.coTapText then
            utimer.remove(this.coTapText)
            this.coTapText = nil
        end
    end
    if(canIntoNext==false)then
        --return;
    end
    for i=1,#NowComicTab do
        destroyImmediate(NowComicTab[i]);
    end
    if this.delayTimerId then
        utimer.remove(this.delayTimerId)
        this.delayTimerId = nil
    end
    --跳过剧情
    if this.NowStory then
        local _storyDic = {}
        _storyDic.story_id = this.NowStory.f_StoryID
        _storyDic.subtitle_id = this.NowStory.f_StoryContent
        _storyDic.story_type = StoryMgr.showType
        TAManager.TrackByDictionary("story_jump",_storyDic)
    end
    NowComicTab={};
    MovieImage.visible = false;
    isAuto=false;
    btn_auto.text=getLanguage("Story_1");
    this.closeThis();
end
--弹出跳过界面
function UIStory.JumpThisTrigger()
    jumpController.selectedIndex = 1;
    --txJumptext.transform.parent.gameObject:SetActive(true);
    resMgr:LoadSpritePrefab(NowChapter.f_JumpImage,function(sp)
        ImgPanelJump.texture = NTexture.New(sp.texture);
    end);
    txJumptext.text=getLanguage(NowChapter.f_StoryText);
    txJumpName.text=getLanguage(NowChapter.f_Name);
end

function UIStory.IsInProcess()
    return #NowStoryIDTable~=0;
end
--关闭跳过界面
function UIStory.CloseJump()
    jumpController.selectedIndex = 0;
end
--确认跳过
function UIStory.ConfirmJumpThisTrigger()
    if not this.IsClickable() then
        return
    end
    if(#tapArr~=0)then
        textinfo.text=tapStr;
        tapArr={};
        canIntoNext=true;
        if this.coTapText then
            utimer.remove(this.coTapText)
            this.coTapText = nil
        end
        return;
    end
    if(canIntoNext==false or isChoose)then
        return;
    end
    for i=1,#NowComicTab do
        destroyImmediate(NowComicTab[i]);
    end
    NowComicTab={};
    MovieImage.visible = false;
    this.TransitionExit()
end

function UIStory.closeThis()
    if this.coTapText then
        utimer.remove(this.coTapText)
        this.coTapText = nil
    end
    this.btn_bullet_chat_title.text = getLanguage("BulletChat_BulletOff")
    this.cur_bullet_chat_open = false
    this.btn_bullet_chat_ctrl.selectedIndex = 0
    DestoryUI(PanelNames.UIBulletChat)
    if mosaicTimerId then
        utimer.remove(mosaicTimerId)
        mosaicTimerId = nil
    end
    closeUI(PanelResNames.UIStory)
    partnerHandler.tryReqPartnerInteract()
    AudioManager.RefreshBGM()
    if logicMgr.StoryMgr.cur_chapter_id == 5001013 then
        logicMgr.StoryMgr.ShowStoryById(1001011,EnumConst.StoryShowType.createRole,logicMgr.StoryMgr.callback)
    else
        if logicMgr.StoryMgr.cur_chapter_id ~= 5001012 and logicMgr.StoryMgr.cur_chapter_id ~= 5001011 then
            if logicMgr.StoryMgr.callback then
                logicMgr.StoryMgr.callback()
                logicMgr.StoryMgr.callback = nil
            end
        else
            FireEvent(Config.EventType.PerformBattlePlay)
        end
    end
    logicMgr.GuideMgr.Resume(GuideMgr.PauseType.StoryPause)
end

function UIStory.autoPlay()
    if(isAuto)then
        isAuto=false;
        btn_auto.text=getLanguage("Story_1");
        utimer.remove(this.autoPlayTimerId)
    else
        isAuto=true;
        btn_auto.text=getLanguage("Story_2");
        this.ResetAutoTime()
        this.autoPlayTimerId = utimer.timeCall(this.OnUpdate,100,-1)
    end
end
function UIStory.ResetAutoTime()
    this.curAutoTime = 0
    this.autoTime = this.defaultAutoTime
end
--過度下個小内容
function UIStory.ScreenDark()
    darkScreen:Play(this.ColorEnd);
end

function UIStory.ColorEnd()
    --Util.DoColor(blackCover,Color(0,0,0,0),1)
    --blackCover.gameObject:SetActive(false);
    this.InitContent();
end

function UIStory.ScreenLight()

end
function UIStory.Log(str1,str2,str3,str4)
    if Config.DEBUG_STORY then
        str1 = str1 or ""
        str2 = str2 or ""
        str3 = str3 or ""
        str4 = str4 or ""
        log(str1..str2..str3..str4)
    end
end
---------------------------------------
--- 弹幕系统相关
---------------------------------------
function UIStory.OperateBulletChat()
    if logicMgr.FuncOpenManager.isOpen(Config.FuncOpenType.BulletChat)  then
        if this.cur_bullet_chat_open then
            this.btn_bullet_chat_title.text = getLanguage("BulletChat_BulletOff")
            this.cur_bullet_chat_open = false
            this.btn_bullet_chat_ctrl.selectedIndex = 0
            closeUI(PanelNames.UIBulletChat)
        else
            this.btn_bullet_chat_title.text = getLanguage("BulletChat_BulletOn")
            this.cur_bullet_chat_open = true
            this.btn_bullet_chat_ctrl.selectedIndex = 1
            showUI(PanelNames.UIBulletChat, 1)
        end
        --local key = logicMgr.HeroManager.GetRoleId().."uistory_switch"
        --Util.SetPlayerPrefs(key, tostring(this.cur_bullet_chat_open))
    end
end

function UIStory.PauseAutoPlay()
    --[[if isAuto then
        isAuto=false;
        btn_auto.text=getLanguage("Story_1")
        utimer.remove(this.autoPlayTimerId)
    end--]]
end
---------------------------------------
--- end
---------------------------------------

return UIStory;
